﻿namespace Tszy.Unlimited.Base.Extensions
{
    /// <summary>
    ///
    /// </summary>
    public static class ListExtensions
    {
        #region 获得二维数组中，每一维之间的所有组合方式

        /// <summary>
        /// 获得二维数组中，每一维之间的所有组合方式。
        /// </summary>
        /// <remarks>
        /// 1 → 4 → 7
        /// 2 ↘ 5 ↘ 8
        /// 3    6    9
        ///
        /// 即：
        /// r1 = 1 × 4 × 7
        /// r2 = 1 × 4 × 8
        /// r3 = 1 × 4 × 9
        /// r4 = 1 × 5 × 7
        /// ……
        /// rn = 3 × 6 × 9
        ///
        /// result = { r1, r2, r3, r4 …… rn }
        /// </remarks>
        /// <typeparam name="T"></typeparam>
        /// <param name="sourceElements"></param>
        /// <returns></returns>
        public static List<List<T>> GetArrayCombinationList<T>(this List<List<T>> sourceElements)
        {
            var resul = sourceElements.GetArrayCombinationList(new List<T>(), 0).ToList();

            return resul;
        }

        private static List<List<T>> GetArrayCombinationList<T>(this List<List<T>> sourceElements, List<T> saveElements, int currentIndex)
        {
            var nextIndex = currentIndex + 1;

            if (sourceElements.Count == nextIndex)
            {
                // 表示当前为最后一个元素。
                var newList = new List<List<T>>();

                foreach (var sourceElement in sourceElements[currentIndex])
                {
                    var targetElementList = new List<T>(saveElements)
                    {
                        sourceElement
                    };

                    newList.Add(targetElementList);
                }

                return newList;
            }
            else
            {
                var newList = new List<List<T>>();

                foreach (var sourceElement in sourceElements[currentIndex])
                {
                    var targetElementList = new List<T>(saveElements)
                    {
                        sourceElement
                    };

                    var target = GetArrayCombinationList(sourceElements, targetElementList, nextIndex);

                    foreach (var targetItem in target)
                    {
                        newList.Add(targetItem);
                    }
                }

                return newList;
            }
        }

        #endregion 获得二维数组中，每一维之间的所有组合方式
    }
}